package com.atguigu.lease.web.admin.service.impl;

import com.atguigu.lease.common.constant.RedisConstant;
import com.atguigu.lease.common.exception.LeaseException;
import com.atguigu.lease.common.result.ResultCodeEnum;
import com.atguigu.lease.web.admin.service.LoginService;
import com.atguigu.lease.web.admin.vo.login.CaptchaVo;
import com.atguigu.lease.web.admin.vo.login.LoginVo;
import com.wf.captcha.SpecCaptcha;
import com.wf.captcha.base.Captcha;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Service
public class LoginServiceImpl implements LoginService {

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    //前端请求并获取验证码和key，后端在redis服务器上存一对key value值，最后在登录的时候验证所有信息
    //本方法需要调用redis和开源的一个验证码，多以需要导入对应的场景启动器
    @Override
    public CaptchaVo getCaptcha() {
        //通过开源的验证码生成器，生成一个验证码
        SpecCaptcha specCaptcha = new SpecCaptcha(130, 48, 4);
        specCaptcha.setCharType(Captcha.TYPE_DEFAULT);

        //调用方法生成一个唯一字符串
        String code = specCaptcha.text().toLowerCase();
        //生成一个redis前缀和随机uuid对象
        String key = RedisConstant.ADMIN_LOGIN_PREFIX + UUID.randomUUID();
        //生成验证码图片
        String image = specCaptcha.toBase64();
        //redis里面添加一对字符串key value
        stringRedisTemplate.opsForValue().set(key,code,RedisConstant.ADMIN_LOGIN_CAPTCHA_TTL_SEC, TimeUnit.SECONDS);

        return new CaptchaVo(image,key);
    }


    //登录
    @Override
    public String login(LoginVo loginVo) {
        //1.判断验证码是否存在
        if(!StringUtils.hasText(loginVo.getCaptchaCode())){
            throw new LeaseException(ResultCodeEnum.ADMIN_CAPTCHA_CODE_NOT_FOUND);
        }
        //2.判断验证码是否合理
        //3.判断账号是否存在
        //4.校验用户是否被禁
        //5.校验用户密码
        //6.创建并返回token
        return null;
    }


}
